package org.wutopia.labcloud.library.common.utility;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;

import java.text.ParseException;
import java.util.Date;
import java.util.Set;
import java.util.UUID;

public class JwtUtility {



    public static final String TOKEN_TYPE = "bearer";

    public static final Integer EXPIRES_IN = 3600;

    // 密钥（实际应从安全存储中读取，如配置中心）
    private static final String SECRET_KEY = "your-secure-256-bit-secret-my-secret-key-is-very-long";

    public static String generateAccessToken(Long id, String username,  Set<String> authorities) throws JOSEException {
        // 1. 构建 JWT 声明
        JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
                .subject(id.toString())                     // 用户 ID
                .claim("username", username)        // 用户名称（自定义声明）
                .claim("authorities", authorities)  // 用户权限（自定义声明）
                .issueTime(new Date())               // 签发时间
                .expirationTime(new Date(System.currentTimeMillis() + 3600 * 1000)) // 过期时间（1小时后）
                .jwtID(UUID.randomUUID().toString()) // JWT 唯一标识
                .build();

        // 2. 创建签名器（使用 HS256 算法）
        JWSSigner signer = new MACSigner(SECRET_KEY.getBytes());

        // 3. 构建 JWT 对象并签名
        SignedJWT signedJWT = new SignedJWT(
                new JWSHeader(JWSAlgorithm.HS256), // 头部指定算法
                claimsSet
        );

        signedJWT.sign(signer);

        // 4. 序列化为紧凑格式的 JWT 字符串
        return signedJWT.serialize();
    }

    public static String generateRefreshToken(Long userId) throws JOSEException {
        JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
                .subject(userId.toString())
                .issueTime(new Date())
                .expirationTime(new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000)) // 7天有效期
                .build();

        SignedJWT signedJWT = new SignedJWT(
                new JWSHeader(JWSAlgorithm.HS256),
                claimsSet
        );
        signedJWT.sign(new MACSigner(SECRET_KEY.getBytes()));

        return signedJWT.serialize();
    }

    public static String refreshToken(String accessToken) throws ParseException, JOSEException {

        // 1. 解析并验证 refreshToken
        SignedJWT refreshToken = SignedJWT.parse(accessToken);
        refreshToken.verify(new MACVerifier(SECRET_KEY.getBytes()));
        JWTClaimsSet claims = refreshToken.getJWTClaimsSet();

        // 2. 检查过期时间
        if (claims.getExpirationTime().before(new Date())) {

        }

        // 3. 生成新 accessToken
        String userId = claims.getSubject();
//            List<String> roles = loadUserRoles(userId); // 从数据库加载最新权限
//            String newAccessToken = generateAccessToken(userId, roles);

//        return ResponseEntity.ok(Map.of("accessToken", newAccessToken));
        return null;
    }


    public static JWTClaimsSet verifyAndParseToken(String token) throws Exception {
        // 1. 解析 JWT
        SignedJWT signedJWT = SignedJWT.parse(token);

        // 2. 验证签名
        JWSVerifier verifier = new MACVerifier(SECRET_KEY.getBytes());
        if (!signedJWT.verify(verifier)) {
            throw new SecurityException("无效的 JWT 签名");
        }

        // 3. 提取声明信息
        JWTClaimsSet claims = signedJWT.getJWTClaimsSet();

        Date expirationTime = claims.getExpirationTime();

        if(expirationTime.before(new Date())) {
            throw new Exception("Token 过期");
        }

        return claims;
    }

}
